<template>
  <a-drawer v-model:visible="vdata.visible" :maskClosable="false" width="44%">
    <template #title>
      <div style="display:flex;justify-content:space-between;align-items:center;">
        <span>{{ vdata.isDetail ? '活动详情' : vdata.isAdd ? '新建活动' : '修改活动' }}</span>
        <a-button v-if="!vdata.isDetail" @click="handleOkFunc(true)">保存草稿</a-button>
      </div>
    </template>
    <div class="container">
      <a-steps progress-dot :current="vdata.currentStep" direction="vertical" style="width: 20%;" @change="handleStepChange">
        <a-step title="基础信息配置" />
        <a-step title="参与条件配置" />
        <a-step title="活动奖品配置" />
      </a-steps>
      <!-- 基础信息配置 -->
      <ActivityBasicInfo
        v-if="vdata.currentStep === 0"
        ref="stepForm0Ref"
        v-model:modelValue="vdata.saveObject"
        :isDetail="vdata.isDetail"
        :payAuthList="vdata.payAuthList"
        :rules="vdata.step0Rules"
      />
  
      <!-- 活动参与条件配置 -->
      <ActivityLimitUser v-if="vdata.currentStep === 1" ref="stepForm1Ref" v-model:modelValue="vdata.saveObject['activityLimitUser']" :isDetail="vdata.isDetail" />
  
      <!-- 活动奖品配置模块 -->
      <ActivityAwardList v-if="vdata.currentStep === 2" ref="stepForm2Ref" v-model:modelValue="vdata.saveObject['activityAwardList']" :isDetail="vdata.isDetail" :award-type="'3'" />
  
      <div class="drawer-btn-center">
        <a-button v-if="vdata.currentStep != 0" style="margin-right:8px" @click="onSteps(-1)">
          <step-backward-outlined />
          上一步
        </a-button>
        <a-button v-if="vdata.currentStep != 2" style="margin-right:8px" @click="onSteps(1)">
          <step-forward-outlined />
          下一步
        </a-button>
        <a-button v-if="vdata.currentStep == 2 && !vdata.isDetail" type="primary" :loading="vdata.btnLoading" @click="handleOkFunc(false)">
          <check-outlined />
          创建
        </a-button>
      </div>
    </div>
  </a-drawer>
</template>
  
  <script lang="ts" setup>
  import ActivityBasicInfo from '@/views/activity/activityCreate/components/ActivityBasicInfo.vue'
  import ActivityLimitUser from '@/views/activity/activityCreate/components/ActivityLimitUser.vue'
  import ActivityAwardList from '@/views/activity/activityCreate/components/ActivityAwardList.vue'
  import { reactive, defineExpose, getCurrentInstance } from 'vue'
  import { req, API_URL_ACTIVITY_DETAILS, $activityAddOrEdit, $uploadPicToGzh } from '@/api/manage'
  import dayjs from 'dayjs'
  
  // 回调函数
  const props = defineProps(['callbackFunc'])
  // 获取当前实例
  const { proxy }: any = getCurrentInstance()
  // 绑定弹窗
  const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
  // 数据源
  const vdata: any = reactive({
    visible: false,
    currentStep: 0,
    saveObject: {}, // 保存的活动对象
    step0Rules: {
    imgUrl: [{ required: false }],
    entryway: [ { required: true, message: '请选择活动入口', trigger: 'blur' } ],
  }
  })
  
  /**
   * 切换步骤
   */
  function onSteps(step: number) {
    if (step < 0) {
      vdata.currentStep--
    } else {
      proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].validateFields().then(() => {
        vdata.currentStep++
      }).catch(() => {})
    }
  }
  /**
   * 步骤点击切换 详情页专属
   */
   function handleStepChange(step){
    if(!vdata.isDetail) return // 非详情页不处理
    if(step == vdata.currentStep) return // 相同步数不处理
    vdata.currentStep = step
  }
  /**
   * 公众号素材上传
   */
   async function handleUploadPic(agentNo, imgUrl) {
    if(!agentNo || !imgUrl) return
    try {
      const res = await $uploadPicToGzh({ agentNo, imgUrl })
      vdata.saveObject.thumbMediaId = res
    } catch (error) {
      vdata.saveObject.thumbMediaId = ''
      vdata.saveObject.imgUrl = ''
    }
  }
  
  /**
   * 提交表单
   */
  function handleOkFunc(isDraft) {
    // 清理校验
    clearFieldValidate()
    // 表单校验
    proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].validateFields(isDraft ? ['activityName','litePath'] : undefined).then(async () => {
      // 处理公众号素材上传-----------------------------------------------------------
      vdata.btnLoading = true
      await handleUploadPic(vdata.saveObject.agentNo, vdata.saveObject.imgUrl)
      const MESSAGE = vdata.isAdd ? '创建活动' : '修改活动'
      const METHOD = vdata.isAdd ? 'POST' : 'PUT'
      const requestData:any = {
        ...JSON.parse(JSON.stringify(vdata.saveObject)),
        belongToPlatform: vdata.saveObject.belongToPlatform ? vdata.saveObject.belongToPlatform.join(',') : '',
        entryway: vdata.saveObject.entryway ? vdata.saveObject.entryway.join(',') : '',
        payAuthId: vdata.saveObject.payAuthId ? vdata.saveObject.payAuthId : null,
        activityTemplateNo: vdata.activityTemplateNo,
        state: isDraft ? 0 : 1,
      }
      if(vdata.isAdd){
        requestData.activityNo = `ACNO${dayjs().format('YYYYMMDDHHmmss')}`
      }
      // 第二步参与条件配置activityLimitUser 数据处理--------------------------------------------------------------第二步
      const { activityLimitUser = {} } = requestData
      if (activityLimitUser.isOnlyOneTimes === 0 || !activityLimitUser.onlyOneTimes) {
        activityLimitUser.onlyOneTimes = 0
      }
      if(activityLimitUser.periodType === 0 || !activityLimitUser.periodTimes){
        activityLimitUser.periodTimes = 0
      }
      if (activityLimitUser.specialType !== 0 && activityLimitUser.specialContent) {
        activityLimitUser.specialContent = activityLimitUser.specialContent.join(',')
      } else {
        delete activityLimitUser.specialContent
      }
      if (activityLimitUser.timeType === 1 && activityLimitUser.timeStartEnd) {
        activityLimitUser.timeStart = activityLimitUser.timeStartEnd[0]
        activityLimitUser.timeEnd = activityLimitUser.timeStartEnd[1]
      } else {
        delete activityLimitUser.timeStart
        delete activityLimitUser.timeEnd
      }
      // 请求数据处理结束 发起请求 ---------------------------------------------------------------------------------请求数据处理结束 发起请求
      $activityAddOrEdit(METHOD, requestData).then(() => {
        $infoBox.message.success(MESSAGE)
        props.callbackFunc()
        onClose()
      }).finally(() => {
        vdata.btnLoading = false
      })
    })
  }
  
  
  /**
  * 打开抽屉
  * @param activityId 编辑活动ID
  * @param record 活动详情
  * @param payAuthList 支付授权列表
  * @param isDetail 是否为详情页
  */
  function show(activityId, { activityTemplateNo, activityCode }, payAuthList, isDetail) {
    vdata.activityTemplateNo = activityTemplateNo
    vdata.activityCode = activityCode
    vdata.payAuthList = payAuthList
    vdata.isAdd = !activityId
    vdata.isDetail = isDetail
    // 清除字段验证
    clearFieldValidate()
    // 数据重置
    vdata.currentStep = 0
    vdata.saveObject = {
      // 基础信息默认值 根据不同活动具体而定 不写在公共组件ActivityBaseInfo中
      litePath: '/pagesActivity/ACTE027/index',
      litePath2: null,
      payAuthId: null,
      belongToPlatform: ['MARKETING'],
      activityImg:'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/yx/374a1ab7-b43f-417d-85da-808e4cf9167e.png'
    }
    if(vdata.isAdd){
      vdata.visible = true
    }else{
      // 获取活动详情
      req.list(API_URL_ACTIVITY_DETAILS, { activityId, activityTemplateNo }).then((result) => {
        vdata.saveObject = JSON.parse(JSON.stringify(result))
        const { sTime, eTime, entryway, belongToPlatform, activityLimitUser = {} } = vdata.saveObject
        const { onlyOneTimes, specialType, specialContent, timeType, timeStart, timeEnd } = activityLimitUser
        // 第一步数据处理
        vdata.saveObject.activityTime = (sTime && eTime) ? [sTime, eTime] : []
        vdata.saveObject.entryway = entryway !== '' ? entryway.split(',') : []
        vdata.saveObject.belongToPlatform = belongToPlatform !== '' ? belongToPlatform.split(',') : []
        // 第二步数据处理,处理限制条件
        activityLimitUser.isOnlyOneTimes = onlyOneTimes === 0 ? 0 : 1
        activityLimitUser.specialContent = (specialType !== 0 && specialContent) ? specialContent.split(',') : []
        activityLimitUser.timeStartEnd = (timeType === 1 && timeStart && timeEnd) ? [timeStart, timeEnd] : null
        vdata.visible = true
      })
    }
  }
  /**
   * 清除字段验证
   */
   function clearFieldValidate(){
    console.log(proxy.$refs['stepForm' + vdata.currentStep + 'Ref'])
    if (proxy.$refs['stepForm' + vdata.currentStep + 'Ref'] != undefined) {
      proxy.$refs['stepForm' + vdata.currentStep + 'Ref'].clearValidate() // 清除验证
    }
  }
  
  /**
  * 关闭抽屉
  */
  function onClose() {
    vdata.visible = false
  }
  
  /**
  * 暴露方法
  */
  defineExpose({ show })
  </script>
  
  <style lang="less" scoped>
  .container{
    width: 100%;
    height: 100%;
    display: flex;
    padding-bottom: 30px;
  }
  :deep(.ant-steps){
    width: 20%;
    flex-shrink: 0
  }
  </style>